<template>
     <head>
     <meta charset="UTF-8">
      <title>CreateClub
      </title>
    </head>
    <body>

    
    <el-container>
    <!-- <el-header>
    <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
     <el-breadcrumb-item :to="{path:'/'}">社团</el-breadcrumb-item>
     <el-breadcrumb-item :to="{path:'/'}">创建社团</el-breadcrumb-item>
    </el-breadcrumb>
     </el-header> -->

    <el-main>
        <div class="CreateClubTable">
          <div class="form-container">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
            <el-row>
              <el-col :span="11">
   
  
          <el-form-item label="社团名称" prop="clubname">
            <el-input v-model="ruleForm.clubname"></el-input>
          </el-form-item>
          <el-form-item label="社长姓名" prop="leadername">
            <el-input v-model="ruleForm.leadername"></el-input>
          </el-form-item>
          <el-form-item label="社长学号" prop="leaderID">
            <el-input v-model="ruleForm.leaderID"></el-input>
          </el-form-item>

          <el-form-item label="社团类型" prop="clubtype">
            <el-select v-model="ruleForm.clubtype" placeholder="请选择社团类型...">
              <el-option label="思想政治类" value=1></el-option>
              <el-option label="学术科技类" value=2></el-option>
              <el-option label="体育竞技类" value=3></el-option>
              <el-option label="志愿公益类" value=4></el-option>
              <el-option label="文化艺术类" value=5></el-option>
            </el-select>
          </el-form-item>

          <!-- 社团所在校区 -->
          <el-form-item label="所在校区" prop="address">
            <el-select v-model="ruleForm.address" placeholder="请选择校区...">
              <el-option label="南校区" value=1></el-option>
              <el-option label="北校区" value=2></el-option>
              <el-option label="珠海校区" value=3></el-option>
              <el-option label="深圳校区" value=4></el-option>
              <el-option label="北校区" value=5></el-option>
              <el-option label="五校园" value=6></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="开展单位" prop="level">
              <el-radio-group v-model="ruleForm.level" @change="handleLevelChange">
                <el-radio label="校级">校级</el-radio>
                <el-radio label="院级">院级</el-radio>
              </el-radio-group>
              <el-form-item prop="college">      
              <el-input  v-if="ruleForm.level === '院级'" v-model="ruleForm.college" placeholder="请输入具体学院" style="margin-left: 10px;"></el-input>
            </el-form-item>
            </el-form-item>

            <el-form-item label="社团联系电话" prop="clubPhone">
              <el-input v-model="ruleForm.clubPhone"></el-input>
            </el-form-item>
            <el-form-item label="社团联系邮箱" prop="clubMail">
              <el-input v-model="ruleForm.clubMail"></el-input>
            </el-form-item>
    </el-col>
    <el-col :span="1">

    </el-col>
      <el-col :span="12">

        <el-form-item label="业务指导老师姓名" prop="teacherName">
          <el-input v-model="ruleForm.teacherName"></el-input>
        </el-form-item>
        <el-form-item label="业务指导老师工号" prop="teacherID">
          <el-input v-model="ruleForm.teacherID"></el-input>
        </el-form-item>
        <el-form-item label="业务指导老师电话" prop="teacherPhone">
          <el-input v-model="ruleForm.teacherPhone"></el-input>
        </el-form-item>
        <el-form-item label="行政指导老师姓名" prop="AdminName">
          <el-input v-model="ruleForm.AdminName"></el-input>
        </el-form-item>
        <el-form-item label="行政指导老师工号" prop="AdminID">
          <el-input v-model="ruleForm.AdminID"></el-input>
        </el-form-item>
        <el-form-item label="行政指导老师电话" prop="AdminPhone">
          <el-input v-model="ruleForm.AdminPhone"></el-input>
        </el-form-item>

      </el-col>
  </el-row>

  
  
  

  <!-- 社团简介 -->
    <el-form-item label="社团简介" prop="Introduction">
    <el-input type="textarea" v-model="ruleForm.Introduction"></el-input>
  </el-form-item>
  
  <!-- 社团宗旨 -->
  <el-form-item label="社团宗旨" prop="createAim">
    <el-input type="textarea" v-model="ruleForm.createAim"></el-input>
  </el-form-item>


  <!-- 社团申请理由 -->
  <el-form-item label="申请理由" prop="createReason">
    <el-input type="textarea" v-model="ruleForm.createReason"></el-input>
  </el-form-item>

  <el-form-item label="申请表文件" >
<a href="https://digital-baituan-filestore.oss-cn-beijing.aliyuncs.com/files/defaultFile/%E3%80%8A%E5%88%9B%E5%BB%BA%E7%A4%BE%E5%9B%A2%E7%94%B3%E8%AF%B7%E8%A1%A8%E3%80%8B.docx">《创建社团申请表》</a>
  </el-form-item>

<el-form-item label="上传申请表：" >
  <input  type="file" @change="handleFileChange">
</el-form-item>

<!-- <label  class="custom-file-upload">
  <span>选择文件</span>
  <input type="file" @change="handleFileChange">
</label> -->


  <!-- 确认按钮和重置按钮 -->
  <el-form-item>
    <el-button type="primary" @click="handleCreate()">确定申请</el-button>
    <el-button type="primary" @click="resetForm('ruleForm')">重置信息</el-button>
  </el-form-item>
</el-form>
</div>

            <el-row>
                <el-col :span="12">

                </el-col>

                <el-col :span="12">

            </el-col>
            </el-row>
        </div>

    </el-main>
    </el-container>

  </body>
    </template>
    
    <script>
    // eslint-disable-next-line no-unused-vars
    import axios from 'axios';
    import { ElMessage } from 'element-plus';
    export default {
   
     name: 'CreateClub',
     data(){
        return{
          kind:2, //文件类型：创建社团文件
          create_state:'',//表示创建的状态 1表示能够创建
          currentTime:'',
            ruleForm: {
              clubname:'',
              leadername:'',
              leaderID:'',
              clubtype:'',
              address:'',
              level:'',
              college:'',
              createAim:'',
              createReason:'',
              teacherName:'',//业务指导老师
              teacherID:'',
              teacherPhone:'',
              AdminName:'', //行政指导老师
              AdminID:'',
              AdminPhone:'',
              Introduction:'', //社团简介
        },
     rules: {
      clubname:[{required: true, message: '请输入活动名称', trigger: 'blur'}],
              leadername:[{required: true,message: '请输入社长姓名', trigger: 'blur'}],
              leaderID:[{required: true,message: '请输入社长学号', trigger: 'blur'}],
              clubtype:[{required: true,message: '请选择社团类型', trigger: 'change'}],
              address:[{required: true,message: '请选择社团地址', trigger: 'change'}],
              clubPhone:[{ required: true, message: '请输入联系电话', trigger: 'blur' }],
              clubMail:[{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }],
              level:[{required: true,message: '请选择社团等级', trigger: 'change'}],
              college:[{required: true,message: '请输入所属学院', trigger: 'blur'}],
              createAim:[{required: true,message: '请填写社团宗旨', trigger: 'blur'}],
              createReason:[{required: true,message: '请填写申请理由', trigger: 'blur'}],
              teacherName:[{required: true,message: '请选择指导老师姓名', trigger: 'blur'}],
              // teacherPhone:[{required: true,message: '请填写电话号码', trigger: 'blur'},
              // { max: 11, message: '请输入正确的手机号码', trigger: 'blur' }],
              teacherID:[{required: true,message: '请输入老师工号', trigger: 'blur'}],
              AdminName:{required: true,message: '请输入老师姓名', trigger: 'blur'},
              AdminID:[{required: true,message: '请输入老师工号', trigger: 'blur'}],
              // AdminPhone:[{}]
              Introduction:[{required: true,message: '请填写社团简介', trigger: 'blur'}], //社团简介
          
        }
      };
    },
    methods:{
      download(url) {
  const xhr = new XMLHttpRequest(); // 注意：这里是 XMLHttpRequest，而不是 newXMLHttpRequest()
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();

  xhr.onload = function() {
    const fileBlob = xhr.response;
    const fileUrl = URL.createObjectURL(fileBlob);
    console.log(fileUrl);

    const elementA = document.createElement('a');
    elementA.setAttribute('href', fileUrl);

    elementA.innerHTML = '下载';
    elementA.setAttribute('download', '《创建社团申请表》.docx');
    elementA.style.display = 'none'; // 隐藏下载链接

    document.body.appendChild(elementA); // 将链接添加到页面中
    elementA.click(); // 模拟点击下载

    // 清理创建的 URL 对象
    URL.revokeObjectURL(fileUrl);
  };
},
      
      handleFileChange(event) {
      this.selectedFile = event.target.files[0];
    },
    async uploadFile() {
      if (!this.selectedFile) {
        alert('Please select a file.');
        return;
      }

      const fileType = await this.getFileType(this.selectedFile); // 假设有一个获取文件类型的方法 getFileType

      if (fileType === 0) {
        alert('Unsupported file type.');
        return;
      }

      const formData = new FormData();
      formData.append('file', this.selectedFile);
      formData.append('kind', this.kind);
      formData.append('FileType', fileType); // 将FileType字段添加到FormData中
      try {
        const response = await axios.post('http://localhost:8080/uploadFile', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        console.log('Success:', response.data);
        alert('File uploaded successfully!'); //8081端口显示：....
      } catch (error) {
        console.error('Error:', error);
        alert('Failed to upload file.');
      }
    },

    async getFileType(file) {
  const fileName = file.name.toLowerCase();
  const fileType = file.type;

  if (fileName.endsWith('.docx') || fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
    return 1; // docx 文件
  } else if (fileName.endsWith('.pdf') || fileType === 'application/pdf') {
    return 2; // pdf 文件
  } else {
    return 0; // 不支持的文件类型
  }
},
      // 处理申请表文件的函数
    //   handlePreview(file) {
    //   // 文件预览操作
    // },
    // handleRemove(file, fileList) {
    //   // 文件移除操作
    // },

    // 上传社团图片之前的检查
    beforeUploadPic(file) {
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      
      if (!isJPGOrPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      return isJPGOrPNG;
    },

    // eslint-disable-next-line no-unused-vars
    beforeUploadFile(file) {
      
      return true;
    },

    // eslint-disable-next-line no-unused-vars
    beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }?`);
      },
    
      // 上传申请表
      handleSuccess(response, file) {
      // 文件上传成功后的回调
      console.log('File uploaded successfully:', response, file);


    },

    getCurrentDateTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1，并且保证两位数
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    return formattedDateTime;
    },

    submitForm(formName) {
      // 检查表单是否通过验证
        this.$refs[formName].validate((valid) => {

          if (valid) {
            this.currentTime = this.getCurrentDateTime;
            const CreateClubData = new FormData();
            CreateClubData.append('uid',this.$store.state.userinfo.account);
            CreateClubData.append('Cname',this.ruleForm.clubname)
            CreateClubData.append('Type',this.ruleForm.clubtype)
            CreateClubData.append('Address',this.ruleForm.address)
            CreateClubData.append('leadername',this.ruleForm.leadername)
            CreateClubData.append('leaderID',this.ruleForm.leaderID)
            CreateClubData.append('college',this.ruleForm.college)
            CreateClubData.append('createAim',this.ruleForm.createAim)
            CreateClubData.append('createReason',this.ruleForm.createReason)
            CreateClubData.append('teacherName',this.ruleForm.teacherName)
            CreateClubData.append('teacherID',this.ruleForm.teacherID)
            CreateClubData.append('teacherPhone',this.ruleForm.teacherPhone)
            CreateClubData.append('AdminName',this.ruleForm.AdminName)
            CreateClubData.append('AdminID',this.ruleForm.AdminID)
            CreateClubData.append('AdminPhone',this.ruleForm.AdminPhone)
            CreateClubData.append('clubPhone',this.ruleForm.clubPhone)
            CreateClubData.append('clubMail',this.ruleForm.clubMail)
            CreateClubData.append('Introduction',this.ruleForm.Introduction)
            CreateClubData.append('CreateTime',this.currentTime)
                       
            axios.post('api/club/createClub', CreateClubData)
            .then(response => {
              this.create_state = response.data.data.state //获取创建状态
              if(this.create_state ==2){
                this.$message({
                message: '无法找到社长信息！请重新填写！',
                type: 'error'
              });
              }else if(this.create_state ==3){
                this.$message({
                message: '无法找到业务指导老师信息！请重新填写！',
                type: 'error'
              });
              }else if(this.create_state ==4){
                this.$message({
                message: '无法找到行政指导老师信息！请重新填写！',
                type: 'error'
              });
              }
              else{
                this.uploadFile();

                ElMessage.success("您已成功提交创建社团申请！");
              console.log('Form submitted successfully:', response);
              }
              
            })
            .catch(error => {
              console.error('Error submitting form:', error);
            });
          } 
          
          else {
            alert('请将信息填写完整！')
            console.log('error submit!!');
            return false;
          }
        });
      },
      handleCreate(){
        this.submitForm('ruleForm');
       
      },

      handleLevelChange(value) {
      if (value === '校级') {
        this.ruleForm.college = '校级';
      }else{
        this.ruleForm.college = '';
      }
    },
    //重置表单的信息
    resetForm(formName) {
        this.$refs[formName].resetFields();
        this.$message({
                message: '已重置信息！',
                type: 'success'
              });
      }
    

    }
    }
    </script>
    
    <style scoped>
    body {
  font-family: Arial, sans-serif;
  /* background-color: rgb(107, 235, 111); */
  display: flex;
  justify-content: center;
  align-items: center;
  /* height: 100vh; */
  /* margin: 0; */
}

    button {
  background-color: #127817;
  color: white;
  border: none;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #145e0a;
}

.form-container{


  margin-left: 200px;
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  width: 900px;
}

/* el-input[type="text"],
el-input[type="email"],
textarea {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
} */

textarea {
  resize: vertical; /* 垂直方向可拉伸 */
}

.custom-file-upload {
  display: inline-block;
  padding: 8px 12px;
  cursor: pointer;
  background-color: #b43131;
  border: 1px solid #d45050;
  border-radius: 4px;
}

.custom-file-upload input[type="file"] {
  display: none;
}

    </style>